<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/*总数字资源model*/

class ResourceTotal extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_total';


    /*关联活动类型*/
    public function conBigType()
    {
        return $this->hasOne(ResourceType::class, 'id', 'big_type_id');
    }


    /**
     * 检索 mysql 数据 （全数据检索）
     * @param keywords 检索条件
     * @param resource_business_id 资源商id
     * @param big_type_id 系统大类
     */
    public function getFilterLists($field = null, $keywords, $resource_business_id = null, $big_type_id = null, $limit = 10)
    {
        $manage_resource_business_ids = request()->manage_info['resource_business_ids'] ?? [];

        //获取敏感词
        // $sensitiveWordModel = new SensitiveWord();
        // $sensitive_word = $sensitiveWordModel->getSensitiveWordALL();

        if (empty($field)) {
            $field = [
                'r.id',
                'guid',
                'resource_business_id',
                'title',
                'author',
                'isbn',
                'press',
                'pre_time',
                'r.img',
                'r.intro',
                'r.create_time',
                'r.big_type_id',
                'r.type_id',
            ];
        }
        $res = $this->from($this->getTable() . ' as r')->select($field)
            ->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('title', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($resource_business_id, $big_type_id) {
                //类型筛选
                if (!empty($resource_business_id)) {
                    $query->where('resource_business_id', $resource_business_id);
                }
                //系统大类
                if (!empty($big_type_id)) {
                    $query->where('big_type_id', $big_type_id);
                }
            })
            // ->where(function ($query) use ($sensitive_word) {
            //     if ($sensitive_word) {
            //         foreach ($sensitive_word as $item) {
            //             $query->where('title', 'not like', "%$item%");
            //         }
            //     }
            // })->where(function ($query) use ($sensitive_word) {
            //     if ($sensitive_word) {
            //         foreach ($sensitive_word as $item) {
            //             $query->where('author', 'not like', "%$item%");
            //         }
            //         $query->orWhereNull('author');
            //     }
            // })
            ->where('is_mask', 1)
            ->where(function ($query) use ($manage_resource_business_ids) {
                if ($manage_resource_business_ids) {
                    $manage_resource_business_ids = is_array($manage_resource_business_ids) ? $manage_resource_business_ids : explode(',', $manage_resource_business_ids);
                    $manage_resource_business_ids = array_map('intval', $manage_resource_business_ids); //强制转换为整型，字符串类型，检索时很慢
                    $query->whereIn('resource_business_id', $manage_resource_business_ids);
                }
            })
            ->where('r.is_del', 1)
            ->where('n.is_del', 1)
            ->orderByDesc('r.id')
            ->limit($limit)
            ->get()
            ->toArray();
        return $res;
    }

    /**
     * 检索 mysql 数据 （全数据检索）
     * @param keywords 检索条件
     * @param resource_business_id 资源商id
     * @param big_type_id 系统大类
     * @param type_id 系统小类 数组形式
     * @param page int 当前页
     * @param limit int 分页大小
     * 
     * @param except_big_type_id 需要排除的大类型id  多个逗号拼接
     * @param except_resource_total_type_id 需要排除的资源类型id
     * @param except_reading_id 需要排除的资源书单id
     * @param except_read_id 需要排除的每日荐书id
     * @param except_system_type_id 需要排除的系统类型id
     * @param is_recom 是否推荐  1 推荐 2 不推荐
     * @param sort 排序字段 null 1 默认排序 2 浏览量排序 3 出版社排序
     * @param limit int 分页大小
     */
    public function lists($keywords, $resource_business_id = null, $big_type_id = null, $type_id = null, $except_big_type_id = null, $except_resource_total_type_id = null, $except_reading_id = null, $except_system_type_id = null, $except_read_id = null, $sort = null, $is_recom = null, $limit = 10)
    {
        $manage_resource_business_ids = request()->manage_info['resource_business_ids'] ?? [];

        if ($sort == 1) {
            $sort = 'is_recom ASC,id DESC';
        } elseif ($sort == 2) {
            $sort = 'browse_num DESC,id DESC'; //browse_num DESC,id DESC 解决点赞量全为0时，数据错乱问题
        } elseif ($sort == 3) {
            $sort = 'pre_time DESC,id DESC';
        } else {
            $sort = 'id DESC';
        }

        //获取敏感词
        // $sensitiveWordModel = new SensitiveWord();
        // $sensitive_word = $sensitiveWordModel->getSensitiveWordALL();

        $except_resource_total_type_resource_guids = [];
        if ($except_resource_total_type_id) {
            $resourceTotalTypeIntentionModel = new ResourceTotalTypeIntention();
            $except_resource_total_type_resource_guids = $resourceTotalTypeIntentionModel->getResourceTotalTypeResourceGuid($except_resource_total_type_id);
        }
        $except_reading_resource_ids = [];
        if ($except_reading_id) {
            $resourceReadingListBookModel = new ResourceReadingListBook();
            $except_reading_resource_ids = $resourceReadingListBookModel->getResourceReadingListBookId($except_reading_id);
        }
        $except_read_resource_ids = [];
        if ($except_read_id) {
            $resourceReadRecomBookModel = new ResourceReadRecomBook();
            $except_read_resource_ids = $resourceReadRecomBookModel->getResourceReadRecomBookId($except_read_id);
        }
        $except_system_type_resource_ids = [];
        if ($except_system_type_id) {
            $resourceSystemTypeIntentionModel = new ResourceSystemTypeIntention();
            $except_system_type_resource_ids = $resourceSystemTypeIntentionModel->getResourceSystemTypeIntentionResourceId($except_system_type_id);
        }
        //  DB::enableQueryLog();
        $res = $this->from($this->getTable() . ' as r')->select([
            'r.id',
            'r.guid',
            'r.resource_business_id',
            'r.title',
            'r.author',
            'r.isbn',
            'r.press',
            'pre_time',
            'r.img',
            'r.intro',
            'r.create_time',
            'r.big_type_id',
            'r.type_id',
            'r.browse_num',
            'r.is_recom'
        ])->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->with('conBigType', function ($query) {
                $query->select('id', 'type_name')->where('is_del', 1);
            })
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('title', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($resource_business_id, $big_type_id, $type_id, $is_recom, $except_resource_total_type_resource_guids, $except_reading_resource_ids, $except_read_resource_ids, $except_system_type_resource_ids) {
                //类型筛选
                if (!empty($resource_business_id)) {
                    $query->where('resource_business_id', $resource_business_id);
                }
                //系统大类
                if (!empty($big_type_id)) {
                    $big_type_id_arr = !is_array($big_type_id) ? explode(',', $big_type_id) : $big_type_id;
                    $big_type_id_arr = array_map('intval', $big_type_id_arr); //强制转换为整型，字符串类型，检索时很慢
                    $query->whereIn('big_type_id', $big_type_id_arr);
                }
                //小类
                if (!empty($type_id)) {
                    $type_id = !is_array($type_id) ? explode(',', $type_id) : $type_id;
                    $type_id = array_map('intval', $type_id); //强制转换为整型，字符串类型，检索时很慢
                    $query->whereIn('type_id', $type_id);
                }
                if ($except_resource_total_type_resource_guids) {
                    $query->whereNotIn('r.guid', $except_resource_total_type_resource_guids); //排除已选择的
                }
                if ($except_reading_resource_ids) {
                    $query->whereNotIn('r.id', $except_reading_resource_ids); //排除已选择的
                }
                if ($except_read_resource_ids) {
                    $query->whereNotIn('r.id', $except_read_resource_ids); //排除已选择的
                }
                if ($except_system_type_resource_ids) {
                    $query->whereNotIn('r.id', $except_system_type_resource_ids); //排除已选择的
                }
                if ($is_recom) {
                    $query->where('is_recom', $is_recom);
                }
            })
            ->where(function ($query) use ($except_big_type_id) {
                if ($except_big_type_id) {
                    $except_big_type_id = is_array($except_big_type_id) ? $except_big_type_id : explode(',', $except_big_type_id);
                    $query->whereNotIn('big_type_id', $except_big_type_id);
                }
            })
            ->where(function ($query) use ($manage_resource_business_ids) {
                if ($manage_resource_business_ids) {
                    $manage_resource_business_ids = is_array($manage_resource_business_ids) ? $manage_resource_business_ids : explode(',', $manage_resource_business_ids);
                    $manage_resource_business_ids = array_map('intval', $manage_resource_business_ids); //强制转换为整型，字符串类型，检索时很慢
                    $query->whereIn('resource_business_id', $manage_resource_business_ids);
                }
            })
            ->where('is_mask', 1)
            ->where('r.is_del', 1)
            ->where('n.is_del', 1)
            // ->orderBy('is_recom')
            ->orderByRaw($sort)
            ->paginate($limit)
            ->toArray();
        //dd(DB::getQueryLog());
        return $res;
    }

    /**
     * 根据类型检索数据
     */
    public function getResourceListByBigTypeId($big_type_id = null, $keywords = null, $limit = 10)
    {
        $manage_resource_business_ids = request()->manage_info['resource_business_ids'] ?? [];

        //获取敏感词
        // $sensitiveWordModel = new SensitiveWord();
        // $sensitive_word = $sensitiveWordModel->getSensitiveWordALL();
        return $this->from($this->getTable() . ' as r')
            ->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->select([
                // 'r.id',
                'guid',
                'resource_business_id',
                'title',
                'author',
                'isbn',
                'press',
                'pre_time',
                'img',
                'intro',
                'r.create_time',
                'r.big_type_id',
                'r.type_id',
                'r.is_recom'
            ])->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('title', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($big_type_id) {
                if ($big_type_id) {
                    $query->where('big_type_id', $big_type_id);
                }
            })->where(function ($query) use ($manage_resource_business_ids) {
                if ($manage_resource_business_ids) {
                    $manage_resource_business_ids = is_array($manage_resource_business_ids) ? $manage_resource_business_ids : explode(',', $manage_resource_business_ids);
                    $manage_resource_business_ids = array_map('intval', $manage_resource_business_ids); //强制转换为整型，字符串类型，检索时很慢
                    $query->whereIn('resource_business_id', $manage_resource_business_ids);
                }
            })->where('is_mask', 1)
            ->where('r.is_del', 1)
            ->where('n.is_del', 1)
            ->orderByDesc('r.id')
            ->limit($limit)
            ->get()
            ->toArray();
    }

    /**
     * 检索 mysql 数据 （单个资源商数据检索,也可以获取总的）
     * @param keywords 检索条件
     * @param resource_business_id 资源商id
     * @param big_type_id 系统大类
     * @param type_id 系统小类
     * @param page int 当前页
     * @param limit int 分页大小
     * @param sort 排序字段 null 1 默认排序 2 浏览量排序 3 出版社排序
     * @param is_recom 是否推荐  1 推荐 2 不推荐
     */
    public function getResourceListByBusinessNameId($keywords = null, $resource_business_id = null, $big_type_id = null, $type_id = null, $sort = null, $is_recom = null, $limit = 10)
    {
        $manage_resource_business_ids = request()->manage_info['resource_business_ids'] ?? [];
        $field = [
            'r.id',
            'guid',
            'resource_business_id',
            'title',
            'author',
            'isbn',
            'press',
            'pre_time',
            'r.img',
            'r.intro',
            'r.create_time',
            'r.big_type_id',
            'r.type_id',
            'r.browse_num',
            'r.is_recom',
            'r.original_create_time',
        ];
        if ($resource_business_id == 3) {
            if ($sort == 1) {
                $sort = 'is_recom ASC,read_sum DESC,id DESC';
            } elseif ($sort == 2) {
                $sort = 'browse_num DESC,read_sum DESC,id DESC'; //browse_num DESC,id DESC 解决点赞量全为0时，数据错乱问题
            } elseif ($sort == 3) {
                $sort = 'pre_time DESC,read_sum DESC,id DESC';
            } else {
                $sort = 'is_recom ASC,read_sum DESC,id DESC';
            }
        } elseif ($resource_business_id == 4) {
            if ($sort == 1) {
                $sort = 'is_recom ASC,issue_year DESC,id DESC';
            } elseif ($sort == 2) {
                $sort = 'browse_num DESC,issue_year DESC,id DESC'; //browse_num DESC,id DESC 解决点赞量全为0时，数据错乱问题
            } elseif ($sort == 3) {
                $sort = 'pre_time DESC,issue_year DESC,id DESC';
            } else {
                $sort = 'is_recom ASC,issue_year DESC,id DESC';
            }
            $field = [
                'r.id',
                'guid',
                'resource_business_id',
                'title',
                'author',
                'isbn',
                'press',
                'pre_time',
                'r.img',
                'r.intro',
                'r.create_time',
                'r.big_type_id',
                'r.type_id',
                'r.browse_num',
                'r.is_recom',
                'r.original_create_time',
                'r.issue_year'
            ];
        } else {
            if ($sort == 1) {
                $sort = 'is_recom ASC,id DESC';
            } elseif ($sort == 2) {
                $sort = 'browse_num DESC,id DESC'; //browse_num DESC,id DESC 解决点赞量全为0时，数据错乱问题
            } elseif ($sort == 3) {
                $sort = 'pre_time DESC,id DESC';
            } else {
                $sort = 'is_recom ASC,id DESC';
            }
        }
        //$sort = 'is_recom ASC';
        // if (empty($resource_business_id)) {
        //     return false; //不支持查询
        // }
        $resource_business_id_arr = [];
        if (!empty($resource_business_id)) {
            $model = $this->getResourceTotalModel($resource_business_id);
            if (empty($model)) return false;

            $resource_business_id_arr[] = $resource_business_id;
        } else {
            $model = $this; //直接查询所有数据
            $resource_business_id_arr = ResourceBusinessName::where('is_del', 1)->pluck('id')->toArray(); //删除的不查询
            $resource_business_id_arr = array_map('intval', $resource_business_id_arr); //强制转换为整型，字符串类型，检索时很慢
        }
        //    DB::enableQueryLog();
        $res = $model->from($model->getTable() . ' as r')
            ->select($field)->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->with('conBigType', function ($query) {
                $query->select('id', 'type_name')->where('is_del', 1);
            })
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('title', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($big_type_id, $type_id, $is_recom) {
                //系统大类
                if (!empty($big_type_id)) {
                    $query->where('big_type_id', $big_type_id);
                }
                //小类
                if (!empty($type_id)) {
                    $query->where('type_id', $type_id);
                }
                if ($is_recom) {
                    $query->where('is_recom', $is_recom);
                }
            })
            ->where(function ($query) use ($manage_resource_business_ids) {
                if ($manage_resource_business_ids) {
                    $manage_resource_business_ids = is_array($manage_resource_business_ids) ? $manage_resource_business_ids : explode(',', $manage_resource_business_ids);
                    $manage_resource_business_ids = array_map('intval', $manage_resource_business_ids); //强制转换为整型，字符串类型，检索时很慢
                    $query->whereIn('resource_business_id', $manage_resource_business_ids);
                }
            })
            ->whereIn('resource_business_id', $resource_business_id_arr)
            ->where('is_mask', 1)
            ->where('n.is_del', 1)
            ->where('r.is_del', 1)
            ->orderByRaw($sort)
            ->paginate($limit)
            ->toArray();

        // dd(DB::getQueryLog());
        return $res;
    }


    /**
     * 获取书籍详情
     * @param id  书籍id
     * @param guid  书籍guid  和 书籍id 2选一
     * @param resource_business_id  资源商id
     */
    public function detail($resource_business_id, $id = null, $guid = null)
    {
        if (empty($id) && empty($guid)) {
            return false;
        }
        if (empty($resource_business_id)) {
            $res = $this->select([
                'id',
                'guid',
                'resource_business_id',
                'big_type_id',
                'title',
                'author',
                'isbn',
                'press',
                'pre_time',
                'img',
                'intro',
                'create_time',
                'type_id',
                'is_recom',
                'browse_num'
            ])->where(function ($query) use ($id, $guid) {
                if ($id) {
                    $query->where('id', $id);
                } else {
                    $query->where('guid', $guid);
                }
            })->where('is_del', 1)
                ->first();
            if ($res) {
                $is_exists_chapter = ResourceBusinessName::where('id', $res->resource_business_id)->value('is_exists_chapter');
                $res->is_exists_chapter = $is_exists_chapter == 1 ? true : false; //是否存在章节，有则可以获取
            }
        } else {
            $model = $this->getResourceTotalModel($resource_business_id);
            if (empty($model)) return false;
            $res = $model->detail($id, $guid);
        }
        //增加返回期号
        if (in_array($res['resource_business_id'], [4, 10])) {
            $model = $this->getResourceTotalModel($res['resource_business_id']);
            $res['issue_name'] = $model->where('guid', $res['guid'])->value('issue_name');
        }
        return $res;
    }

    /**
     * 添加浏览量
     * @param guid  书籍guid
     * @param resource_business_id  资源商id
     * @param browse_num  浏览量
     */
    public function addBrowseNum($resource_business_id, $guid, $browse_num = 1)
    {
        if (empty($guid)) {
            return false;
        }
        $browse_num = empty($browse_num) ? 1 : $browse_num;
        $model = $this->getResourceTotalModel($resource_business_id);
        if (empty($model)) return false;
        $res = $model->where('guid', $guid)->where('is_del', 1)->increment('browse_num', $browse_num);
        if ($res) {
            ResourceTotal::where('guid', $guid)->where('is_del', 1)->increment('browse_num', $browse_num); //更新总表数据id
        }

        return $res;
    }


    public function addData($data)
    {
        $res = $this->where('resource_business_id', $data->resource_business_id)->where('guid', $data->guid)->first();
        if (empty($res)) {
            //修改
            $res = new self();
        }
        $res->big_type_id = $data->big_type_id;
        $res->type_id = $data->type_id;
        $res->resource_business_id = $data->resource_business_id;
        $res->guid = $data->guid;
        $res->title = $data->title;
        $res->author = $data->author ?? '';
        $res->isbn = $data->isbn ?? '';
        $res->press = $data->press ?? '';
        $res->pre_time = $data->pre_time ?? '';
        $res->img = $data->img;
        $res->intro = $data->intro ?? '';
        $res->data_unique_id = $data->data_unique_id; //数据唯一id
        $res->original_create_time = $data->original_create_time ?? null; //原上架时间
        $res->original_change_time = $data->original_change_time ?? null; //原修改时间
        $res->data_unique_id = $data->data_unique_id; //数据唯一id
        $res->change_time = date('Y-m-d H:i:s'); //数据唯一id
        $res->is_del = 1; //有可能是之前下架，现在重新上架
        $res->save();
        return true;
    }

    public function deleteData($guid)
    {
        $obj = new self();
        $res = $obj->where('guid', $guid)->where('is_del', 1)->first();
        if (empty($res)) {
            return true;
        }
        $res->is_del = 2;
        $res->save();
        return true;
    }


    /**
     *获取推荐资源
     */
    public function getRecomResourceLists($big_type_id, $type_id, $limit = 9)
    {
        $res = $this->from($this->getTable() . ' as r')->select([
            'r.id',
            'guid',
            'resource_business_id',
            'title',
            'author',
            'isbn',
            'press',
            //  'pre_time',
            'r.img',
            //   'r.intro',
            //  'r.create_time',
            'r.big_type_id',
            'r.type_id',
            //  'r.is_recom'
        ])->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->with('conBigType', function ($query) {
                $query->select('id', 'type_name')->where('is_del', 1);
            })
            ->where(function ($query) use ($big_type_id, $type_id) {
                //系统大类
                if (!empty($big_type_id)) {
                    $query->where('big_type_id', $big_type_id);
                }
                if (!empty($type_id)) {
                    $query->where('type_id', $type_id);
                }
            })
            ->where('r.is_mask', 1)
            ->where('r.is_del', 1)
            ->where('n.is_del', 1)
            // ->inRandomOrder()  // 随机返回走不了索引，所以很慢
            ->limit($limit)
            ->get()
            ->toArray();

        return $res;
    }

    /**
     * 根据资源商id获取资源大类id
     * @param resource_business_id  资源商id
     */
    public function getBigTypeIdByResourceId($resource_business_id, $type_id)
    {
        //获取敏感词
        // $sensitiveWordModel = new SensitiveWord();
        // $sensitive_word = $sensitiveWordModel->getSensitiveWordALL();
        $res = $this->where('is_del', 1)
            ->where('resource_business_id', $resource_business_id)
            ->where(function ($query) use ($type_id) {
                if ($type_id) {
                    $query->where('type_id', $type_id);
                }
            })
            // ->where(function ($query) use ($sensitive_word) {
            //     if ($sensitive_word) {
            //         foreach ($sensitive_word as $item) {
            //             $query->where('title', 'not like', "%$item%");
            //         }
            //     }
            // })->where(function ($query) use ($sensitive_word) {
            //     if ($sensitive_word) {
            //         foreach ($sensitive_word as $item) {
            //             $query->where('author', 'not like', "%$item%");
            //         }
            //         $query->orWhereNull('author');
            //     }
            // })
            ->where('is_mask', 1)
            ->groupBy('big_type_id')
            ->pluck('big_type_id')
            ->toArray();

        return $res;
    }

    /**
     * 获取资源商
     * @param resource_business_id  资源商id
     * @param big_type_id  大类id
     */
    public function getResourceNum($resource_business_id, $big_type_id = null, $type_id = null)
    {
        $key = md5('getResourceNum-' . $resource_business_id . '-' . $big_type_id . '-' . $type_id);
        $resource_num = Cache::get($key);
        if ($resource_num) return $resource_num;
        //获取敏感
        // $sensitiveWordModel = new SensitiveWord();
        // $sensitive_word = $sensitiveWordModel->getSensitiveWordALL();
        $resource_num = $this->from($this->getTable() . ' as r')
            ->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->where(function ($query) use ($resource_business_id, $big_type_id, $type_id) {
                //系统大类
                if (!empty($resource_business_id)) {
                    $query->where('resource_business_id', $resource_business_id);
                }
                if (!empty($big_type_id)) {
                    $query->where('big_type_id', $big_type_id);
                }
                if (!empty($type_id)) {
                    $query->where('type_id', $type_id);
                }
            })
            // ->where(function ($query) use ($sensitive_word) {
            //     if ($sensitive_word) {
            //         foreach ($sensitive_word as $item) {
            //             $query->where('title', 'not like', "%$item%");
            //         }
            //     }
            // })->where(function ($query) use ($sensitive_word) {
            //     if ($sensitive_word) {
            //         foreach ($sensitive_word as $item) {
            //             $query->where('author', 'not like', "%$item%");
            //         }
            //         $query->orWhereNull('author');
            //     }
            // })
            ->where('is_mask', 1)
            ->where('n.is_del', 1)
            ->where('r.is_del', 1)
            ->count();

        Cache::put($key, $resource_num, 30 * 60);

        return $resource_num;
    }


    /**
     * 把所有屏蔽的数据都恢复
     */
    public function maskDataRecover()
    {
        $this->where('is_mask', 2)->update(['is_mask' => 1]); //恢复所有屏蔽的数据
        $resource_business_id_arr = [1, 2, 3, 4, 5, 6, 7, 8];
        foreach ($resource_business_id_arr as $val) {
            $resource_business_name = ResourceBusinessName::where('id', $val)->where('is_del', 1)->first();
            if (empty($resource_business_name)) {
                continue;
            }
            $model = $this->getResourceTotalModel($val);
            $model->where('is_mask', 2)->update(['is_mask' => 1]); //恢复所有屏蔽的数据(按表恢复)
        }
        return true;
    }
    /**
     * 按照敏感词屏蔽所有的数据
     */
    public function sensitiveResourceMask()
    {
        $res = $this->getSensitiveResourceInfo();
        //如果不存在不管，因为上一个接口已经全部恢复了
        if ($res) {
            $this->whereIn('id', array_column($res, 'id'))->update(['is_mask' => 2]); //屏蔽数据
            //修改单个表的数据
            foreach ($res as $key => $val) {
                $model = $this->getResourceTotalModel($val['resource_business_id']);
                $model->where('guid', $val['guid'])->update(['is_mask' => 2]); //恢复所有屏蔽的数据(按表恢复)
            }
        }
        return true;
    }

    /**
     * 获取需要屏蔽的数据id
     * @param resource_business_id  资源商id
     * @param big_type_id  大类id
     */
    public function getSensitiveResourceInfo($resource_business_id = null)
    {
        //获取敏感
        $sensitiveWordModel = new SensitiveWord();
        $sensitive_word = $sensitiveWordModel->getSensitiveWordALL();
        if (empty($sensitive_word)) {
            return [];
        }
        //   DB::enableQueryLog();
        $resource_data = $this->from($this->getTable() . ' as r')
            ->select('r.id', 'guid', 'resource_business_id')
            ->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->where(function ($query) use ($resource_business_id) {
                //系统大类
                if (!empty($resource_business_id)) {
                    $query->where('resource_business_id', $resource_business_id);
                }
            })
            ->where(function ($query) use ($sensitive_word) {
                if ($sensitive_word) {
                    foreach ($sensitive_word as $item) {
                        $query->orwhere('title', 'like', "%$item%")->orwhere('author', 'like', "%$item%");
                    }
                }
            })
            ->where('r.is_del', 1)
            ->where('n.is_del', 1)
            ->get()
            ->toArray();
        //     dd(Db::getQueryLog());
        return $resource_data;
    }
    /**
     * 获取资源详情二维码
     */
    public function getResourceQrUrl($big_type_id, $guid)
    {
        $obj = new Controller();
        $host_url = str_replace('/public', '', $obj->getHostUrl());
        if ($big_type_id == 3) {
            //$url = 'https://book.usharego.com/digital_reader_yzq/index?path=pagesDigital/videoDetail/index&guid=' . $guid; //视频详情链接  path 为前端路由地址
            $url = $host_url . '/index?path=pagesDigital/videoDetail/index&guid=' . $guid; //视频详情链接  path 为前端路由地址
        } else {
            //$url = 'https://book.usharego.com/digital_reader_yzq/index?path=pagesDigital/detail/index&guid=' . $guid; //其他资源详情链接
            $url = $host_url . '/index?path=pagesDigital/detail/index&guid=' . $guid; //其他资源详情链接
        }
        //$url = urlencode($url);
        return $url;
    }
   /**
     * 获取资源详情二维码(微信端)
     */
    public function getWechatResourceQrUrl($big_type_id, $guid, $resource_business_id = null)
    {
        $obj = new Controller();
        $host_url = str_replace('/public', '', $obj->getHostUrl());
        if ($big_type_id == 3) {
            $url = $host_url . '/wx/pagesDigital/videoDetail/index?guid=' . $guid . '&resource_business_id=' . $resource_business_id; //视频详情链接  path 为前端路由地址 //视频详情链接  path 为前端路由地址
        } else {
            $url = $host_url . '/wx/pagesDigital/detail/index?guid=' . $guid . '&resource_business_id=' . $resource_business_id; //其他资源详情链接
        }
        return $url;
    }
    /**
     * 获取数据对象
     * @param resource_business_id  资源商id
     */
    public function getResourceTotalModel($resource_business_id)
    {
        switch ($resource_business_id) {
            case 1:
                $model = new ResourceZwzx();
                break;
            case 2:
                $model = new ResourceQqrd();
                break;
            case 3:
                $model = new ResourceYtys();
                break;
            case 4:
                $model = new ResourceBk();
                break;
            case 5:
                $model = new ResourceLeer();
                break;
            case 6:
                $model = new ResourceXyts();
                break;
            case 7:
                $model = new ResourceCxzx();
                break;
            case 8:
                $model = new ResourceZy();
                break;
            case 9:
                $model = new ResourceYrd();
                break;
            case 999:
                $model = new ResourceCdbt();
                break;
            default:
                $model = false;
        }
        return $model;
    }
}
